package com.dd.controller;

import cn.hutool.core.util.StrUtil;
import com.dd.constant.Constant;
import com.dd.model.ConnectionInfo;
import com.dd.service.JdbcConnectionFactory;
import com.dd.service.JdbcDataCompareUtil;
import com.dd.service.JdbcSchemaCompareUtil;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MainController implements Initializable {

    private static final Logger log = LoggerFactory.getLogger(MainController.class);

    @FXML
    private ComboBox<String> sourceDbLink;
    @FXML
    private ComboBox<String> targetDbLink;
    @FXML
    private ComboBox<String> sourceDbComboBox;
    @FXML
    private ComboBox<String> targetDbComboBox;
    @FXML
    private TextField sourceTableTextField;
    @FXML
    private TextArea ddlTextArea;
    @FXML
    private Button compareButton;
    @FXML
    private Button clearButton;
    @FXML
    private Button copyButton;
    @FXML
    private Button selectTablesButton;
    @FXML
    private Label buttonLabel;

    private ObservableList<String> databases = FXCollections.observableArrayList();
    private ObservableList<String> connections = FXCollections.observableArrayList();
    private Map<String, List<String>> dbTablesMap = new HashMap<>();

    @FXML
    private ToggleGroup compareTypeGroup;  // 新增：关联FXML中的ToggleGroup

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initDatabaseComboBoxes();
        initButtons();
        initDbTablesMap();
        buttonLabel.setText("© 2025 " + Constant.APP_NAME);
        compareTypeGroup.getSelectedToggle()
                .setSelected(true);
    }

    private void initDbTablesMap() {
        String[] databases = {"crmx", "crmx_plan", "solux"};
        for (String db : databases) {
            try {
                dbTablesMap.put(db, JdbcSchemaCompareUtil.getDbTables(JdbcConnectionFactory.getSourceConnection(db)));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private void initDatabaseComboBoxes() {
        Map<String, ConnectionInfo> connectionMap = JdbcConnectionFactory.CONNECTION_MAP;
        connections.addAll(connectionMap.keySet());
        sourceDbLink.setItems(connections);
        sourceDbLink.setValue("测试环境");
        sourceDbLink.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if (newValue != null) {
                        JdbcConnectionFactory.sourceConnectionMap.clear();
                        JdbcConnectionFactory.sourceConnectionInfo = connectionMap.get(newValue);
                    }
                });
        targetDbLink.setItems(connections);
        targetDbLink.setValue("生产环境");
        targetDbLink.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if (newValue != null) {
                        JdbcConnectionFactory.tragetConnectionMap.clear();
                        JdbcConnectionFactory.targetConnectionInfo = connectionMap.get(newValue);
                    }
                });

        databases.addAll("crmx", "crmx_plan", "solux");
        sourceDbComboBox.setItems(databases);
        sourceDbComboBox.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if (newValue != null) {
                        selectedTables.clear();
                        sourceTableTextField.clear();
                        targetDbComboBox.setValue(newValue);
                    }
                });
        sourceDbComboBox.getSelectionModel()
                .selectFirst();
    }

    private void initButtons() {
        compareButton.setOnAction(event -> generateDiffDDL());
        clearButton.setOnAction(event -> ddlTextArea.clear());
        // 新增：初始化复制按钮
        copyButton.setOnAction(event -> copyScriptToClipboard());
        // 初始禁用复制按钮，直到有内容可复制
        copyButton.setDisable(true);
        // 监听DDL文本区域变化，控制复制按钮状态
        ddlTextArea.textProperty()
                .addListener((observable, oldValue, newValue) -> {
                    copyButton.setDisable(newValue == null || newValue.trim()
                            .isEmpty());
                });
        // 新增：初始化选择表按钮
        selectTablesButton.setOnAction(event -> showTableSelectionDialog());
        // 监听数据库选择，启用选择表按钮
        sourceDbComboBox.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    selectTablesButton.setDisable(newValue == null);
                });
    }

    // 新增：全局变量，用于存储当前选中的表名集合
    private final Set<String> selectedTables = new HashSet<>();

    private void showTableSelectionDialog() {
        String selectedDb = sourceDbComboBox.getValue();
        if (selectedDb == null) {
            showAlert("请先选择数据库");
            return;
        }

        // 获取当前数据库的表列表
        List<String> tables = dbTablesMap.getOrDefault(selectedDb, Collections.emptyList());
        if (tables.isEmpty()) {
            showAlert("该数据库下没有可用表");
            return;
        }

        // 创建多选对话框
        Dialog<List<String>> dialog = new Dialog<>();
        dialog.setTitle("选择表");
        dialog.setHeaderText("从列表中选择一个或多个表");
        dialog.initOwner((sourceDbComboBox.getScene()
                .getWindow()));
        Image icon = new Image(getClass().getResourceAsStream("/icons/icon.png"));
        Stage dialogStage = (Stage) dialog.getDialogPane()
                .getScene()
                .getWindow();
        dialogStage.getIcons()
                .add(icon);

        // 设置对话框按钮
        ButtonType selectButtonType = new ButtonType("选择", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane()
                .getButtonTypes()
                .addAll(selectButtonType, ButtonType.CANCEL);

        // 创建复选框容器
        VBox checkBoxContainer = new VBox();
        checkBoxContainer.setSpacing(8);
        checkBoxContainer.setPadding(new Insets(10));

        // 为每个表创建复选框，并绑定事件处理
        Map<String, CheckBox> checkBoxMap = new HashMap<>();
        for (String table : tables) {
            CheckBox checkBox = new CheckBox();
            checkBox.setText(table);
            checkBox.setMnemonicParsing(false);

            // 初始化复选框状态，并绑定勾选/取消勾选事件
            checkBox.setSelected(selectedTables.contains(table));
            checkBox.selectedProperty()
                    .addListener((observable, oldValue, newValue) -> {
                        if (newValue) {
                            selectedTables.add(table); // 勾选时添加到全局变量
                        } else {
                            selectedTables.remove(table); // 取消勾选时从全局变量移除
                        }
                        updateTableTextField(); // 实时更新文本框显示
                    });

            checkBoxContainer.getChildren()
                    .add(checkBox);
            checkBoxMap.put(table, checkBox);
        }

        // 创建全选/全不选按钮
        ToggleButton selectAllButton = new ToggleButton("全选");
        selectAllButton.setOnAction(event -> {
            boolean selectAll = selectAllButton.isSelected();
            selectAllButton.setText(selectAll ? "全不选" : "全选");

            // 更新所有复选框状态
            for (CheckBox checkBox : checkBoxMap.values()) {
                checkBox.setSelected(selectAll);
            }
        });

        // 创建主容器，包含滚动面板和按钮
        VBox mainContainer = new VBox(10);
        mainContainer.setPadding(new Insets(0, 0, 10, 0));

        // 创建滚动面板
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setContent(checkBoxContainer);
        scrollPane.setFitToWidth(true);
        scrollPane.setPrefHeight(300);
        scrollPane.setMaxHeight(300);
        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);

        // 创建按钮容器，使用HBox实现水平布局
        HBox buttonContainer = new HBox(10);
        buttonContainer.setPadding(new Insets(0, 10, 0, 10));
        buttonContainer.getChildren()
                .add(selectAllButton);

        mainContainer.getChildren()
                .addAll(scrollPane, buttonContainer);

        dialog.getDialogPane()
                .setContent(mainContainer);
        dialog.getDialogPane()
                .setMinWidth(300);

        // 简化结果转换器：直接返回全局变量中的内容
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == selectButtonType) {
                return new ArrayList<>(selectedTables);
            }
            return null;
        });

        // 显示对话框并处理结果
        dialog.showAndWait()
                .ifPresent(selectedItems -> {
                    updateTableTextField();
                });
    }

    // 新增：更新文本框显示的方法
    private void updateTableTextField() {
        String tablesText = String.join(",", selectedTables);
        sourceTableTextField.setText(tablesText);
    }

    private void showCopySuccessMessage() {
        // 原按钮文本
        String originalText = copyButton.getText();

        // 修改按钮文本为"已复制!"
        copyButton.setText("已复制!");

        // 短暂延迟后恢复原文本
        new Thread(() -> {
            try {
                Thread.sleep(1000); // 1秒
                Platform.runLater(() -> copyButton.setText(originalText));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void generateDiffDDL() {
        log.info("源数据库：{}", JdbcConnectionFactory.sourceConnectionInfo);
        log.info("目标数据库：{}", JdbcConnectionFactory.targetConnectionInfo);

        String sourceDb = sourceDbComboBox.getValue();
        String sourceTables = sourceTableTextField.getText();

        // 比对数据不支持全部
        RadioButton selectedRadio = (RadioButton) compareTypeGroup.getSelectedToggle();
        String compareType = selectedRadio == null ? "结构比对" : selectedRadio.getText();
        if ((sourceTables == null || sourceTables.trim()
                .isEmpty()) && StrUtil.equals(sourceDb, "数据比对")) {
            showAlert("请选择表！");
            return;
        }

        if (sourceTables == null || sourceTables.trim()
                .isEmpty()) {
            List<String> strings = dbTablesMap.get(sourceDb);
            sourceTables = String.join(", ", strings);
        }
        String[] split = sourceTables.split(",");

        // 1. 创建等待弹窗
        Stage waitStage = new Stage();
        waitStage.setTitle("处理中");
        waitStage.initOwner(sourceDbComboBox.getScene()
                .getWindow()); // 关联主窗口，使其模态
        waitStage.initModality(Modality.APPLICATION_MODAL);
        waitStage.setResizable(false);
        waitStage.setWidth(300);
        waitStage.setHeight(250);

        Image icon = new Image(getClass().getResourceAsStream("/icons/icon.png"));
        waitStage.getIcons()
                .add(icon);

        // 2. 弹窗内容：文本提示 + 等待指示器
        VBox content = new VBox(15);
        content.setPadding(new Insets(20));
        content.setAlignment(Pos.CENTER);

        Label waitLabel = new Label(split.length + "张表生成脚本中...");
        ProgressIndicator progressIndicator = new ProgressIndicator(-1.0); // 无限循环动画
        progressIndicator.setPrefSize(50, 50);

        content.getChildren()
                .addAll(waitLabel, progressIndicator);
        waitStage.setScene(new Scene(content));
        waitStage.sizeToScene();

        Window ownerWindow = sourceDbComboBox.getScene()
                .getWindow();
        waitStage.setOnShown(event -> {
            double centerX = ownerWindow.getX() + (ownerWindow.getWidth() - waitStage.getWidth()) / 2;
            double centerY = ownerWindow.getY() + (ownerWindow.getHeight() - waitStage.getHeight()) / 2;
            waitStage.setX(centerX);
            waitStage.setY(centerY);
        });

        // 3. 显示弹窗
        waitStage.show();

        // 4. 启动新线程执行耗时操作
        // 新增：获取用户选择的比对类型
        selectedRadio = (RadioButton) compareTypeGroup.getSelectedToggle();
        compareType = selectedRadio == null ? "结构比对" : selectedRadio.getText();
        if ("结构比对".equals(compareType)) {
            // 执行原有结构比对逻辑
            startThreadHandleGenDDl(sourceTables, sourceDb, waitStage);
        } else {
            // 数据比对暂未实现，提示用户
            Platform.runLater(() -> {
                startThreadHandleDataCompare(sourceDb, split, waitStage);
            });
        }
    }

    private void startThreadHandleGenDDl(String sourceTables, String sourceDb, Stage waitStage) {
        new Thread(() -> {
            StringBuilder ddl = new StringBuilder();
            long startTime = System.currentTimeMillis();

            ExecutorService executor = Executors.newFixedThreadPool(10);
            List<Future<String>> futures = new ArrayList<>();

            try {
                // 执行生成DDL的逻辑
                String[] splitTables = sourceTables.split(",");
                for (String sourceTable : splitTables) {
                    // 提交任务到线程池
                    Future<String> future = executor.submit(() -> handleGenOneTable(sourceTable, sourceDb));
                    futures.add(future);
                }

                // 获取并合并所有结果
                for (Future<String> future : futures) {
                    ddl.append(future.get()); // 这会阻塞直到任务完成
                }

                // 生成完成后，在UI线程更新结果并关闭弹窗
                String finalDdl = ddl.toString()
                        .trim()
                        .isEmpty() ? "没有差异。" : ddl.toString();

                // 计算执行时间
                long executionTime = System.currentTimeMillis() - startTime;

                Platform.runLater(() -> {
                    log.info("DDL生成完成，耗时: " + executionTime + " 毫秒");
                    ddlTextArea.setText(finalDdl);
                    waitStage.close(); // 关闭等待弹窗
                });
            } catch (Exception e) {
                // 计算执行时间（包括异常处理阶段）
                long executionTime = System.currentTimeMillis() - startTime;
                // 异常处理：显示错误信息并关闭弹窗
                Platform.runLater(() -> {
                    log.info("DDL生成失败，耗时: " + executionTime + " 毫秒");
                    showAlert("生成失败：" + e.getMessage());
                    waitStage.close(); // 无论成功与否，都要关闭弹窗
                });
                log.error("生成DDL失败", e);
            } finally {
                // 确保线程池始终被关闭
                executor.shutdownNow();
            }
        }).start();
    }

    private String handleGenOneTable(String tableName, String dbName) {
        long startTime = System.currentTimeMillis();
        StringBuilder ddlTable = new StringBuilder();
        tableName = tableName.trim();
        boolean b = false;
        try {
            b = JdbcSchemaCompareUtil.checkTableExist(JdbcConnectionFactory.getSourceConnection(dbName), tableName);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if (!b) {
            log.error("表 {} 在源数据库中不存在", tableName);
            ddlTable.append("\n")
                    .append("-- ")
                    .append(tableName)
                    .append("表在源数据库中不存在\n");
            return "";
        }
        try {
            if (!JdbcSchemaCompareUtil.checkTableExist(JdbcConnectionFactory.getTargetConnection(dbName), tableName)) {
                String createTableSQL = JdbcSchemaCompareUtil.getCreateTableSQL(dbName, tableName);
                ddlTable.append("\n")
                        .append("-- ")
                        .append(tableName)
                        .append("表新增")
                        .append("\n")
                        .append(createTableSQL)
                        .append("\n");
            } else {
                List<String> strings = JdbcSchemaCompareUtil.compareTableStructure(dbName, tableName);
                if (strings != null && !strings.isEmpty()) {
                    ddlTable.append("\n")
                            .append("-- ")
                            .append(tableName)
                            .append("表变动")
                            .append("\n");
                    for (String item : strings) {
                        ddlTable.append(item)
                                .append("\n");
                    }
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        long executionTime = System.currentTimeMillis() - startTime;
        log.info("{}.{}，耗时: {} 毫秒", dbName, tableName, executionTime);
        return ddlTable.length() == 0 ? "" : ddlTable.toString();
    }


    // 数据比对：生成目标库缺失ID的INSERT语句
    private void startThreadHandleDataCompare(String sourceDb, String[] splitTables, Stage waitStage) {
        new Thread(() -> {
            StringBuilder insertSqls = new StringBuilder();
            long startTime = System.currentTimeMillis();
            ExecutorService executor = Executors.newFixedThreadPool(5); // 数据比对线程池
            List<Future<String>> futures = new ArrayList<>();

            try {
                // 提交多表比对任务
                for (String tableName : splitTables) {
                    String finalTableName = tableName.trim();
                    futures.add(executor.submit(() ->
                            handleSingleTableDataCompare(sourceDb, finalTableName)));
                }

                // 合并结果
                for (Future<String> future : futures) {
                    insertSqls.append(future.get());
                }

                // 处理最终结果
                String result = insertSqls.toString()
                        .trim();
                if (result.isEmpty()) {
                    result = "数据比对完成，未发现目标库缺失的ID数据";
                }

                String finalResult = result;
                Platform.runLater(() -> {
                    ddlTextArea.setText(finalResult);
                    waitStage.close();
                    log.info("数据比对完成，耗时: " + (System.currentTimeMillis() - startTime) + " 毫秒");
                });

            } catch (Exception e) {
                Platform.runLater(() -> {
                    showAlert("数据比对失败：" + e.getMessage());
                    waitStage.close();
                });
                log.error("数据比对异常", e);
            } finally {
                executor.shutdownNow();
            }
        }).start();
    }

    // 单表数据比对：生成缺失ID的INSERT语句
    private String handleSingleTableDataCompare(String dbName, String tableName) {
        long startTime = System.currentTimeMillis();
        StringBuilder tableSql = new StringBuilder();
        String primaryKey = "id"; // 默认主键名，可通过数据库元数据获取

        try {
            // 1. 验证表存在性
            if (!JdbcSchemaCompareUtil.checkTableExist(JdbcConnectionFactory.getSourceConnection(dbName), tableName)) {
                tableSql.append("\n-- 表 ")
                        .append(tableName)
                        .append(" 在源数据库中不存在\n");
                return tableSql.toString();
            }
            if (!JdbcSchemaCompareUtil.checkTableExist(JdbcConnectionFactory.getTargetConnection(dbName), tableName)) {
                tableSql.append("\n-- 表 ")
                        .append(tableName)
                        .append(" 在目标数据库中不存在，无法进行数据比对\n");
                return tableSql.toString();
            }

            // 2. 获取表的主键（优化：从数据库元数据获取，而非硬编码）
            primaryKey =
                    JdbcDataCompareUtil.getPrimaryKeyColumnName(JdbcConnectionFactory.getSourceConnection(dbName), tableName);
            if (primaryKey == null) {
                tableSql.append("\n-- 表 ")
                        .append(tableName)
                        .append(" 未找到主键，跳过比对\n");
                return tableSql.toString();
            }

            // 3. 获取源库和目标库的所有ID
            Set<String> sourceIds = JdbcDataCompareUtil.getTableIds(JdbcConnectionFactory.getSourceConnection(dbName)
                    , tableName, primaryKey);
            Set<String> targetIds = JdbcDataCompareUtil.getTableIds(JdbcConnectionFactory.getTargetConnection(dbName)
                    , tableName, primaryKey);

            // 4. 找出源库独有的ID
            Set<String> missingIds = new HashSet<>(sourceIds);
            missingIds.removeAll(targetIds);

            if (missingIds.isEmpty()) {
                tableSql.append("\n-- 表 ")
                        .append(tableName)
                        .append(" 无缺失数据\n");
                return tableSql.toString();
            }

            // 5. 分批处理大量缺失ID（避免SQL语句过长）
            tableSql.append("\n-- 表 ")
                    .append(tableName)
                    .append(" 缺失数据")
                    .append(missingIds.size())
                    .append("条\n");
            List<String> columnNames =
                    JdbcDataCompareUtil.getTableColumnNames(JdbcConnectionFactory.getSourceConnection(dbName), tableName);

            // 每批处理1000个ID（可根据数据库性能调整）
            int batchSize = 1000;
            List<List<String>> batches = new ArrayList<>();
            List<String> currentBatch = new ArrayList<>();

            for (String id : missingIds) {
                currentBatch.add(id);
                if (currentBatch.size() >= batchSize) {
                    batches.add(new ArrayList<>(currentBatch));
                    currentBatch.clear();
                }
            }
            if (!currentBatch.isEmpty()) {
                batches.add(currentBatch);
            }

            // 分批查询并生成INSERT语句
            for (List<String> batch : batches) {
                List<Map<String, Object>> missingData = JdbcDataCompareUtil.getSourceDataByIds(
                        JdbcConnectionFactory.getSourceConnection(dbName),
                        tableName,
                        primaryKey,
                        new HashSet<>(batch),
                        columnNames
                );

                for (Map<String, Object> data : missingData) {
                    tableSql.append(JdbcDataCompareUtil.generateInsertSql(tableName, columnNames, data))
                            .append(";\n");
                }
            }

        } catch (SQLException e) {
            tableSql.append("\n-- 表 ")
                    .append(tableName)
                    .append(" 比对失败：")
                    .append(e.getMessage())
                    .append("\n");
            log.error("表{}数据比对失败", tableName, e);
        }

        log.info("表{}数据比对完成，耗时: {}毫秒", tableName, System.currentTimeMillis() - startTime);
        return tableSql.toString();
    }


    private Stage createWaitStage(String title, String message) {
        Stage waitStage = new Stage();
        waitStage.setTitle(title);
        waitStage.initOwner(sourceDbComboBox.getScene()
                .getWindow());
        waitStage.initModality(Modality.APPLICATION_MODAL);
        waitStage.setResizable(false);
        waitStage.setWidth(300);
        waitStage.setHeight(250);

        Image icon = new Image(getClass().getResourceAsStream("/icons/icon.png"));
        waitStage.getIcons()
                .add(icon);

        VBox content = new VBox(15);
        content.setPadding(new Insets(20));
        content.setAlignment(Pos.CENTER);
        content.getChildren()
                .addAll(
                        new Label(message),
                        new ProgressIndicator(-1.0)
                );
        waitStage.setScene(new Scene(content));

        // 居中显示
        Window ownerWindow = sourceDbComboBox.getScene()
                .getWindow();
        waitStage.setOnShown(event -> {
            double centerX = ownerWindow.getX() + (ownerWindow.getWidth() - waitStage.getWidth()) / 2;
            double centerY = ownerWindow.getY() + (ownerWindow.getHeight() - waitStage.getHeight()) / 2;
            waitStage.setX(centerX);
            waitStage.setY(centerY);
        });

        return waitStage;
    }


    // 新增：复制脚本到剪贴板的方法
    private void copyScriptToClipboard() {
        String script = ddlTextArea.getText();

        if (script == null || script.trim()
                .isEmpty()) {
            showAlert("没有可复制的脚本内容");
            return;
        }

        // 获取系统剪贴板
        Clipboard clipboard = Clipboard.getSystemClipboard();
        ClipboardContent content = new ClipboardContent();

        // 设置剪贴板内容
        content.putString(script);
        clipboard.setContent(content);

        // 显示复制成功提示
        showCopySuccessMessage();
    }

    @FXML
    private void showDatabaseManageDialog(ActionEvent event) {
        try {
            // 获取主舞台实例（使用主界面组件确保可靠性）
            Stage primaryStage = (Stage) sourceDbComboBox.getScene()
                    .getWindow();
            Stage dialogStage = new Stage();
            dialogStage.setTitle("数据库管理");
            dialogStage.initModality(Modality.APPLICATION_MODAL);
            dialogStage.initOwner(primaryStage);
            Image icon = new Image(getClass().getResourceAsStream("/icons/icon.png"));
            dialogStage.getIcons()
                    .add(icon);

            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/DatabaseManageDialog.fxml"));
            dialogStage.setScene(new Scene(loader.load()));

            // 关键修复：显式居中（在设置场景后调用）
            dialogStage.centerOnScreen();

            dialogStage.showAndWait();
        } catch (Exception e) {
            log.error("打开数据库管理界面失败", e);
            showAlert("打开数据库管理界面失败：" + e.getMessage());
        }
    }

    private void showAlert(String message) {
        new Alert(Alert.AlertType.WARNING, message).show();
    }

    // 新增：关于对话框方法
    public void showAboutDialog(ActionEvent event) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("关于");
        alert.setHeaderText(Constant.APP_NAME);
        alert.setContentText("本工具用于比较生产环境和测试环境数据库表结构差异，自动生成DDL同步脚本。\n版本：" + Constant.VERSION + "\n版权：© 2025 松霖家");

        // 设置对话框居中（假设primaryStage是主舞台实例，需确保已获取）
        Stage primaryStage = (Stage) ((MenuItem) event.getSource()).getParentPopup()
                .getOwnerWindow();
        alert.initOwner(primaryStage);
        alert.initModality(Modality.APPLICATION_MODAL);

        // 仅保留确定按钮
        alert.getButtonTypes()
                .setAll(ButtonType.OK);
        Button okButton = (Button) alert.getDialogPane()
                .lookupButton(ButtonType.OK);
        okButton.setText("确定");

        // 添加图标（假设路径正确）
        Image icon = new Image(getClass().getResourceAsStream("/icons/icon.png"));
        ((Stage) alert.getDialogPane()
                .getScene()
                .getWindow()).getIcons()
                .add(icon);

        alert.showAndWait();
    }

}

